#include "net_access_audit_manager.h"
#include "common.h"

#include <QDebug>

#include <iostream>

NetAccessAuditManager::NetAccessAuditManager(QObject *parent)
    : QObject(parent)
{
}

NetAccessAuditManager::~NetAccessAuditManager()
{
    m_monitors.clear();
}

void NetAccessAuditManager::refresh(const QStringList &ips, const QStringList &ports)
{
    m_ip2Dns.clear();
    m_monitors.clear();
    auto interfaces = PcapMonitor::getAllNetInterfaceNames();
    std::list<std::string> tmpPorts;
    std::list<std::string> tmpIps;
    for (auto ip : ips) {
        auto result = getIpsFromDNS(ip.toStdString());
        tmpIps.insert(tmpIps.end(), result.begin(), result.end());
        for (auto tmpIP : result) {
            m_ip2Dns[tmpIP.c_str()] = ip;
        }
    }
    for (auto port : ports) {
        tmpPorts.insert(tmpPorts.end(), port.toStdString());
    }

    auto rules = PcapMonitor::makeMonitorRule(tmpIps, tmpPorts);
    qInfo() << rules.c_str();
    for (auto interface : interfaces) {
        auto monitor = std::make_shared<PcapMonitor>();
        monitor->setMonitorRule(rules);
        if (monitor->start(interface)) {
            m_monitors.push_back(monitor);
            connect(monitor.get(), &PcapMonitor::accessNotify, this, &NetAccessAuditManager::onAccessNotify);
        }
    }
}

void NetAccessAuditManager::onAccessNotify(const QString &ip, int port)
{
    qInfo() << m_ip2Dns[ip] << ":" << port;
    accessNotify(m_ip2Dns[ip], port);
}
